package com.tkjt.pms.modules.report.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.def.MapExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tkjt.pms.common.IndexParam;
import com.tkjt.pms.common.entity.TkIndexReport;
import com.tkjt.pms.modules.common.service.TkDataConfigService;
import com.tkjt.pms.modules.common.service.TkIndexReportService;
import com.tkjt.pms.modules.report.service.ReportCreator;
import com.tkjt.pms.modules.report.service.ReportExcelService;
import com.tkjt.pms.modules.report.vo.DatagridVO;
import com.tkjt.pms.server.ServerService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service(ReportCreator.SERVICE_REPORT_CREATOR)
public class ReportServerService implements ServerService {

    @Autowired
    private ReportExcelService reportExcelService;
	@Autowired
	private TkIndexReportService tkIndexReportService;
	@Autowired
	private TkDataConfigService tkDataConfigService;
	@Autowired
	private ISysUserService sysUserService;
	
	@Override
	public void doService(IndexParam serverParam) {
		log.info("do report service...");
		String reprotCode = (String)serverParam.getParam("reportCode");
		//tempReport为tk_index_report中的report_code，简报和报表用一套
		String tempReport = reprotCode;
		//isTotal == true 为简报
		boolean isTotal = false;
		if(reprotCode.startsWith("isTotal")){
			isTotal = true;
			tempReport = reprotCode.substring(8);
		}
		String indexYearMonth = (String)serverParam.getParam("indexYearMonth");
		LoginUser loginUser = (LoginUser)serverParam.getParam("loginUser");
		String reportPath = (String)serverParam.getParam("reportPath");
		String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
		try {
			QueryWrapper<TkIndexReport> reportQuery = new QueryWrapper<>();
			reportQuery.lambda().eq(TkIndexReport::getIndexYearMonth,indexYearMonth);
			reportQuery.lambda().eq(TkIndexReport::getReportCode,tempReport);
			reportQuery.lambda().eq(TkIndexReport::getDataType,dataType);
			TkIndexReport tkIndexReport = tkIndexReportService.getOne(reportQuery);
			DatagridVO datagridVO = new DatagridVO();
			datagridVO.setIndexGroup(tkIndexReport.getIndexGroup().equals("1")?"G":"C");

			Map<String, Object> excelDatas = reportExcelService.buildReportExcelData(isTotal,indexYearMonth, tempReport,loginUser,null,datagridVO,dataType);
			ExportParams params = new ExportParams();
			if("RHC".equals(tempReport)){
				params.setTitle("一线单位绩效考核报表");
				params.setSheetName("一线单位");
				params.setSecondTitle("报表创建人:" + loginUser.getRealname());
			}else if("RDP".equals(tempReport)){
				params.setTitle("养康本部绩效考核报表");
				params.setSheetName("事业群");
				params.setSecondTitle("报表创建人:" + loginUser.getRealname());
			}else if("RHCH".equals(tempReport)){
				params.setTitle("一线单位绩效考核报表(领导)");
				params.setSheetName("一线单位");
				params.setSecondTitle("报表创建人:" + loginUser.getRealname());
			}else if("RDPH".equals(tempReport)){
				params.setTitle("养康本部绩效考核报表(领导)");
				params.setSheetName("养康本部");
				params.setSecondTitle("报表创建人:" + loginUser.getRealname());
			}else{
				params.setTitle("我的绩效考核报表");
				params.setSheetName("我的绩效");
				String[] reports = tempReport.split("@");
				QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
				userQueryWrapper.lambda().eq(SysUser::getUsername,reports[0]);
				SysUser sysUser = sysUserService.getOne(userQueryWrapper);
				params.setSecondTitle("报表创建人:" + sysUser.getRealname());
			}

			params.setType(ExcelType.XSSF);
			Map<String,Object> modelMap = new HashMap<>();
			modelMap.put(MapExcelConstants.MAP_LIST, excelDatas.get(MapExcelConstants.MAP_LIST)); //数据集合
			modelMap.put(MapExcelConstants.ENTITY_LIST, excelDatas.get(MapExcelConstants.ENTITY_LIST)); //注解集合
			modelMap.put(MapExcelConstants.PARAMS, params);//参数
			modelMap.put(MapExcelConstants.FILE_NAME, indexYearMonth+"-"+reprotCode+"-"+dataType);//文件名称
			downLoad(modelMap,reportPath);
			Map<String, Object> updateParam = new HashMap<>();
			updateParam.put("reportCode",tempReport);
			updateParam.put("indexYearMonth",indexYearMonth);
			//已生成
			updateParam.put("reportStatus","3");
			updateParam.put("reportDate",new Date());
			updateParam.put("updateDate",new Date());
			updateParam.put("dataType",dataType);
			tkIndexReportService.updateReporByParam(updateParam);

		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> updateParam = new HashMap<>();
			updateParam.put("reportCode",(String)serverParam.getParam("reportCode"));
			updateParam.put("indexYearMonth",indexYearMonth);
			//错误
			updateParam.put("reportStatus","0");
			updateParam.put("dataType",dataType);
			tkIndexReportService.updateReporByParam(updateParam);
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void downLoad(Map<String, Object> model,String reportPath) throws Exception {
		String codedFileName = "临时文件";
		Workbook workbook = ExcelExportUtil.exportExcel((ExportParams)model.get("params"), (List)model.get("data"), (Collection)model.get("mapList"));
		if (model.containsKey("fileName")) {
			codedFileName = (String)model.get("fileName");
		}

		if (workbook instanceof HSSFWorkbook) {
			codedFileName = codedFileName + ".xls";
		} else {
			codedFileName = codedFileName + ".xlsx";
		}
		codedFileName = new String(codedFileName.getBytes("UTF-8"));
		File file = new File(reportPath+"//"+codedFileName);
		if(file.exists()){
			file.delete();
		} else if(!file.exists()){
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		try {
			workbook.write(fileOutputStream);
		}finally {
			fileOutputStream.close();
		}
	}
	
}
